<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品管理附件上传测试</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            max-width: 900px; 
            margin: 0 auto; 
            padding: 20px; 
            background: #f5f5f5;
        }
        .container { 
            background: white; 
            padding: 25px; 
            border-radius: 8px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .section { 
            margin: 20px 0; 
            padding: 15px; 
            border: 1px solid #ddd; 
            border-radius: 5px; 
        }
        .error { background: #fee; border-color: #fcc; }
        .success { background: #efe; border-color: #cfc; }
        .info { background: #eef; border-color: #ccf; }
        .warning { background: #fff3cd; border-color: #ffeaa7; }
        pre { 
            background: #f8f9fa; 
            padding: 12px; 
            border-radius: 4px; 
            overflow-x: auto; 
            font-size: 13px;
            border: 1px solid #e9ecef;
        }
        button { 
            padding: 10px 20px; 
            margin: 8px 5px; 
            cursor: pointer; 
            border: none;
            border-radius: 4px;
            font-weight: 500;
        }
        .btn-primary { background: #007bff; color: white; }
        .btn-danger { background: #dc3545; color: white; }
        .btn-success { background: #28a745; color: white; }
        .btn-info { background: #17a2b8; color: white; }
        input[type="file"] { 
            margin: 10px 0; 
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        .status-ok { background: #28a745; }
        .status-error { background: #dc3545; }
        .status-pending { background: #ffc107; }
        h1 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
        h3 { color: #555; margin-top: 0; }
        .path-display {
            background: #f8f9fa;
            padding: 8px 12px;
            border-radius: 4px;
            font-family: monospace;
            border: 1px solid #dee2e6;
            margin: 5px 0;
        }
    </style>
</head>
<body>
    <h1>🔧 产品管理附件上传测试工具</h1>
    
    <div class="container">
        <div class="section info">
            <h3>📋 测试目标</h3>
            <p>验证产品类型和产品管理表单的图片上传是否正确保存到硬盘中：</p>
            <ul>
                <li>测试控制台API上传功能</li>
                <li>验证文件是否写入硬盘存储</li>
                <li>检查服务重启后文件是否持久化</li>
                <li>确认URL访问路径是否正确</li>
            </ul>
        </div>
    </div>

    <div class="container">
        <h3>🏗️ 当前配置状态</h3>
        <div id="configStatus">
            <div class="section info">
                <p>正在检查配置...</p>
            </div>
        </div>
    </div>

    <div class="container">
        <h3>📤 1. 测试控制台API上传</h3>
        <div class="section">
            <p><strong>API端点:</strong> <code>/apis/api.console.halo.run/v1alpha1/attachments/upload</code></p>
            <p><strong>策略:</strong> <code>default-policy</code></p>
            <input type="file" id="consoleFileInput" accept="image/*" />
            <br>
            <button class="btn-primary" onclick="testConsoleUpload()">🚀 测试控制台上传</button>
            <button class="btn-info" onclick="checkStorageDirectory()">📁 检查存储目录</button>
        </div>
        <div id="consoleResult"></div>
    </div>

    <div class="container">
        <h3>💾 2. 硬盘存储验证</h3>
        <div class="section">
            <p><strong>预期存储路径:</strong></p>
            <div class="path-display">~/.halo2/attachments/upload/</div>
            <button class="btn-success" onclick="listUploadedFiles()">📂 列出已上传文件</button>
            <button class="btn-info" onclick="checkDiskStorage()">💿 检查硬盘存储</button>
        </div>
        <div id="storageResult"></div>
    </div>

    <div class="container">
        <h3>🔄 3. 持久化测试</h3>
        <div class="section warning">
            <p><strong>⚠️ 注意:</strong> 此测试需要重启Halo服务来验证文件持久化。</p>
            <p>上传文件后，请手动重启服务，然后点击下面的按钮验证文件是否仍然存在。</p>
            <button class="btn-danger" onclick="testPersistence()">🔄 测试重启后持久化</button>
        </div>
        <div id="persistenceResult"></div>
    </div>

    <div class="container">
        <h3>🐛 4. 问题诊断</h3>
        <div class="section">
            <button class="btn-info" onclick="diagnoseIssues()">🔍 运行诊断</button>
            <button class="btn-info" onclick="showSystemInfo()">ℹ️ 显示系统信息</button>
        </div>
        <div id="diagnosticResult"></div>
    </div>

    <script>
        let uploadedFiles = [];
        
        // 页面加载时检查配置
        window.onload = function() {
            checkConfiguration();
        };
        
        // 检查当前配置
        async function checkConfiguration() {
            const statusDiv = document.getElementById('configStatus');
            
            try {
                statusDiv.innerHTML = '<div class="section info"><p>🔍 正在检查系统配置...</p></div>';
                
                // 检查系统设置
                const systemResponse = await fetch('/apis/v1alpha1/configmaps/system', {
                    credentials: 'include'
                });
                
                let configHtml = '';
                
                if (systemResponse.ok) {
                    const systemData = await systemResponse.json();
                    const postData = systemData.data?.post ? JSON.parse(systemData.data.post) : {};
                    
                    configHtml += `
                        <div class="section success">
                            <h4><span class="status-indicator status-ok"></span>系统配置</h4>
                            <p><strong>文章附件策略:</strong> <code>${postData.attachmentPolicyName || '未设置'}</code></p>
                            <p><strong>工作目录:</strong> <code>~/.halo2</code></p>
                            <p><strong>附件存储:</strong> <code>~/.halo2/attachments/upload/</code></p>
                        </div>
                    `;
                } else {
                    configHtml += `
                        <div class="section error">
                            <h4><span class="status-indicator status-error"></span>系统配置获取失败</h4>
                            <p>无法获取系统配置 (${systemResponse.status})</p>
                        </div>
                    `;
                }
                
                // 检查存储策略
                try {
                    const policyResponse = await fetch('/apis/storage.halo.run/v1alpha1/policies', {
                        credentials: 'include'
                    });
                    
                    if (policyResponse.ok) {
                        const policyData = await policyResponse.json();
                        const defaultPolicy = policyData.items.find(p => p.metadata.name === 'default-policy');
                        
                        if (defaultPolicy) {
                            configHtml += `
                                <div class="section success">
                                    <h4><span class="status-indicator status-ok"></span>存储策略</h4>
                                    <p><strong>策略名称:</strong> ${defaultPolicy.metadata.name}</p>
                                    <p><strong>显示名称:</strong> ${defaultPolicy.spec.displayName}</p>
                                    <p><strong>模板类型:</strong> ${defaultPolicy.spec.templateName}</p>
                                </div>
                            `;
                        } else {
                            configHtml += `
                                <div class="section error">
                                    <h4><span class="status-indicator status-error"></span>存储策略</h4>
                                    <p>未找到 default-policy 存储策略</p>
                                </div>
                            `;
                        }
                    }
                } catch (error) {
                    configHtml += `
                        <div class="section warning">
                            <h4><span class="status-indicator status-pending"></span>存储策略</h4>
                            <p>无法检查存储策略: ${error.message}</p>
                        </div>
                    `;
                }
                
                statusDiv.innerHTML = configHtml;
                
            } catch (error) {
                statusDiv.innerHTML = `
                    <div class="section error">
                        <h4><span class="status-indicator status-error"></span>配置检查失败</h4>
                        <pre>${error.message}</pre>
                    </div>
                `;
            }
        }
        
        // 测试控制台上传
        async function testConsoleUpload() {
            const fileInput = document.getElementById('consoleFileInput');
            const resultDiv = document.getElementById('consoleResult');
            
            if (!fileInput.files.length) {
                resultDiv.innerHTML = '<div class="section error">❌ 请先选择一个图片文件</div>';
                return;
            }
            
            const file = fileInput.files[0];
            const formData = new FormData();
            formData.append('file', file);
            formData.append('policyName', 'default-policy');
            
            try {
                resultDiv.innerHTML = '<div class="section info">📤 正在上传文件...</div>';
                
                const startTime = Date.now();
                const response = await fetch('/apis/api.console.halo.run/v1alpha1/attachments/upload', {
                    method: 'POST',
                    body: formData,
                    credentials: 'include'
                });
                
                const endTime = Date.now();
                const result = await response.json();
                
                if (response.ok) {
                    const fileInfo = {
                        name: result.metadata?.name,
                        displayName: result.spec?.displayName,
                        size: result.spec?.size,
                        mediaType: result.spec?.mediaType,
                        permalink: result.status?.permalink,
                        uploadTime: new Date().toLocaleString(),
                        duration: endTime - startTime
                    };
                    
                    uploadedFiles.push(fileInfo);
                    
                    resultDiv.innerHTML = `
                        <div class="section success">
                            <h4>✅ 上传成功 (${fileInfo.duration}ms)</h4>
                            <p><strong>文件名:</strong> ${fileInfo.displayName}</p>
                            <p><strong>大小:</strong> ${fileInfo.size} bytes</p>
                            <p><strong>类型:</strong> ${fileInfo.mediaType}</p>
                            <p><strong>访问URL:</strong> <a href="${fileInfo.permalink}" target="_blank">${fileInfo.permalink}</a></p>
                            <details>
                                <summary>完整响应数据</summary>
                                <pre>${JSON.stringify(result, null, 2)}</pre>
                            </details>
                        </div>
                    `;
                    
                    // 自动检查存储目录
                    setTimeout(checkStorageDirectory, 1000);
                    
                } else {
                    resultDiv.innerHTML = `
                        <div class="section error">
                            <h4>❌ 上传失败 (${response.status})</h4>
                            <pre>${JSON.stringify(result, null, 2)}</pre>
                        </div>
                    `;
                }
            } catch (error) {
                resultDiv.innerHTML = `
                    <div class="section error">
                        <h4>❌ 上传异常</h4>
                        <pre>${error.message}</pre>
                    </div>
                `;
            }
        }
        
        // 检查存储目录
        async function checkStorageDirectory() {
            const resultDiv = document.getElementById('consoleResult');
            const currentContent = resultDiv.innerHTML;
            
            try {
                // 通过API获取附件列表来验证存储
                const response = await fetch('/apis/api.console.halo.run/v1alpha1/attachments?page=0&size=10', {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const data = await response.json();
                    const recentFiles = data.items.slice(0, 5);
                    
                    let storageInfo = `
                        <div class="section info">
                            <h4>📁 存储目录检查结果</h4>
                            <p><strong>总文件数:</strong> ${data.total}</p>
                            <p><strong>最近上传的文件:</strong></p>
                            <ul>
                    `;
                    
                    recentFiles.forEach(file => {
                        storageInfo += `
                            <li>
                                <strong>${file.spec.displayName}</strong> 
                                (${file.spec.size} bytes, ${file.spec.mediaType})
                                <br><small>访问路径: ${file.status.permalink}</small>
                            </li>
                        `;
                    });
                    
                    storageInfo += `
                            </ul>
                        </div>
                    `;
                    
                    resultDiv.innerHTML = currentContent + storageInfo;
                } else {
                    resultDiv.innerHTML = currentContent + `
                        <div class="section warning">
                            <h4>⚠️ 存储检查失败</h4>
                            <p>无法获取附件列表 (${response.status})</p>
                        </div>
                    `;
                }
            } catch (error) {
                resultDiv.innerHTML = currentContent + `
                    <div class="section error">
                        <h4>❌ 存储检查异常</h4>
                        <pre>${error.message}</pre>
                    </div>
                `;
            }
        }
        
        // 列出已上传文件
        function listUploadedFiles() {
            const resultDiv = document.getElementById('storageResult');
            
            if (uploadedFiles.length === 0) {
                resultDiv.innerHTML = `
                    <div class="section warning">
                        <h4>⚠️ 暂无上传记录</h4>
                        <p>请先使用上面的上传功能测试文件上传</p>
                    </div>
                `;
                return;
            }
            
            let fileList = `
                <div class="section success">
                    <h4>📋 本次会话上传的文件 (${uploadedFiles.length}个)</h4>
                    <ul>
            `;
            
            uploadedFiles.forEach((file, index) => {
                fileList += `
                    <li>
                        <strong>${file.displayName}</strong> 
                        (${file.size} bytes)
                        <br><small>上传时间: ${file.uploadTime}</small>
                        <br><small>访问路径: <a href="${file.permalink}" target="_blank">${file.permalink}</a></small>
                    </li>
                `;
            });
            
            fileList += `
                    </ul>
                </div>
            `;
            
            resultDiv.innerHTML = fileList;
        }
        
        // 检查硬盘存储
        async function checkDiskStorage() {
            const resultDiv = document.getElementById('storageResult');
            const currentContent = resultDiv.innerHTML;
            
            try {
                // 通过附件API检查存储状态
                const response = await fetch('/apis/api.console.halo.run/v1alpha1/attachments?page=0&size=1', {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const data = await response.json();
                    
                    resultDiv.innerHTML = currentContent + `
                        <div class="section info">
                            <h4>💾 硬盘存储状态</h4>
                            <p><strong>存储路径:</strong> <code>~/.halo2/attachments/upload/</code></p>
                            <p><strong>总附件数:</strong> ${data.total}</p>
                            <p><strong>状态:</strong> <span class="status-indicator status-ok"></span>存储正常</p>
                            <p><em>注意: 文件实际保存在服务器的硬盘中，重启后仍然存在</em></p>
                        </div>
                    `;
                } else {
                    resultDiv.innerHTML = currentContent + `
                        <div class="section error">
                            <h4>❌ 硬盘存储检查失败</h4>
                            <p>无法检查存储状态 (${response.status})</p>
                        </div>
                    `;
                }
            } catch (error) {
                resultDiv.innerHTML = currentContent + `
                    <div class="section error">
                        <h4>❌ 硬盘存储检查异常</h4>
                        <pre>${error.message}</pre>
                    </div>
                `;
            }
        }
        
        // 测试持久化
        async function testPersistence() {
            const resultDiv = document.getElementById('persistenceResult');
            
            try {
                resultDiv.innerHTML = '<div class="section info">🔄 正在测试持久化...</div>';
                
                // 检查之前上传的文件是否仍然存在
                const response = await fetch('/apis/api.console.halo.run/v1alpha1/attachments', {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const data = await response.json();
                    const totalFiles = data.total;
                    
                    resultDiv.innerHTML = `
                        <div class="section ${totalFiles > 0 ? 'success' : 'warning'}">
                            <h4>${totalFiles > 0 ? '✅' : '⚠️'} 持久化测试结果</h4>
                            <p><strong>当前附件总数:</strong> ${totalFiles}</p>
                            ${totalFiles > 0 
                                ? '<p>🎉 文件已成功持久化到硬盘，重启后仍然存在！</p>' 
                                : '<p>⚠️ 未发现附件文件，可能存在存储问题</p>'
                            }
                        </div>
                    `;
                } else {
                    resultDiv.innerHTML = `
                        <div class="section error">
                            <h4>❌ 持久化测试失败</h4>
                            <p>无法检查文件持久化状态 (${response.status})</p>
                        </div>
                    `;
                }
            } catch (error) {
                resultDiv.innerHTML = `
                    <div class="section error">
                        <h4>❌ 持久化测试异常</h4>
                        <pre>${error.message}</pre>
                    </div>
                `;
            }
        }
        
        // 诊断问题
        async function diagnoseIssues() {
            const resultDiv = document.getElementById('diagnosticResult');
            
            resultDiv.innerHTML = '<div class="section info">🔍 正在运行诊断...</div>';
            
            let diagnosticHtml = '';
            
            // 检查API可访问性
            try {
                const apiResponse = await fetch('/apis/api.console.halo.run/v1alpha1/attachments?page=0&size=1', {
                    credentials: 'include'
                });
                
                diagnosticHtml += `
                    <div class="section ${apiResponse.ok ? 'success' : 'error'}">
                        <h4>${apiResponse.ok ? '✅' : '❌'} API可访问性</h4>
                        <p>控制台附件API响应状态: ${apiResponse.status}</p>
                    </div>
                `;
            } catch (error) {
                diagnosticHtml += `
                    <div class="section error">
                        <h4>❌ API可访问性</h4>
                        <p>无法访问控制台API: ${error.message}</p>
                    </div>
                `;
            }
            
            // 检查存储策略
            try {
                const policyResponse = await fetch('/apis/storage.halo.run/v1alpha1/policies', {
                    credentials: 'include'
                });
                
                if (policyResponse.ok) {
                    const policyData = await policyResponse.json();
                    const hasDefaultPolicy = policyData.items.some(p => p.metadata.name === 'default-policy');
                    
                    diagnosticHtml += `
                        <div class="section ${hasDefaultPolicy ? 'success' : 'error'}">
                            <h4>${hasDefaultPolicy ? '✅' : '❌'} 存储策略</h4>
                            <p>default-policy策略: ${hasDefaultPolicy ? '存在' : '不存在'}</p>
                            <p>总策略数: ${policyData.items.length}</p>
                        </div>
                    `;
                }
            } catch (error) {
                diagnosticHtml += `
                    <div class="section error">
                        <h4>❌ 存储策略检查失败</h4>
                        <p>${error.message}</p>
                    </div>
                `;
            }
            
            // 添加建议
            diagnosticHtml += `
                <div class="section info">
                    <h4>💡 诊断建议</h4>
                    <ul>
                        <li>确保Halo服务正在运行</li>
                        <li>检查 ~/.halo2/attachments/upload/ 目录权限</li>
                        <li>验证存储策略配置是否正确</li>
                        <li>查看服务器日志获取详细错误信息</li>
                    </ul>
                </div>
            `;
            
            resultDiv.innerHTML = diagnosticHtml;
        }
        
        // 显示系统信息
        function showSystemInfo() {
            const resultDiv = document.getElementById('diagnosticResult');
            const currentContent = resultDiv.innerHTML;
            
            const systemInfo = `
                <div class="section info">
                    <h4>ℹ️ 系统信息</h4>
                    <p><strong>用户代理:</strong> ${navigator.userAgent}</p>
                    <p><strong>当前时间:</strong> ${new Date().toLocaleString()}</p>
                    <p><strong>页面URL:</strong> ${window.location.href}</p>
                    <p><strong>测试时间:</strong> ${new Date().toISOString()}</p>
                </div>
            `;
            
            resultDiv.innerHTML = currentContent + systemInfo;
        }
    </script>
</body>
</html>